<template>
  <div class="app-container">
    <el-tabs tab-position="left">
      <!-- 供应商认证 Tab Pane -->
      <el-tab-pane :label="status ? '供应商信息' : '供应商认证'">
        <el-card>
          <div class="mb5">
            <el-alert v-if="status == 'approve'" title="审核中，7个工作日内审核" type="info"/>
            <el-alert v-else-if="status == 'reject'" :title="'审核未通过，原因：'+reason" type="error"/>
          </div>
          <el-form ref="applyFormRef" :model="applyData" :rules="applyRules" label-width="90">
            <el-form-item prop="contact_name" label="联系人" :required="status == '' || status == 'reject'">
              <el-input
                v-if="status == '' || status == 'reject'"
                ref="contact_name"
                v-model="applyData.contact_name"
                placeholder="请输入联系人姓名"
                name="contact_name"
                class="h-[48px]"
                style="width: 300px;"/>
              <div v-else>{{ applyData.contact_name }}</div>
            </el-form-item>

            <el-form-item prop="contact_name" label="联系电话" :required="status == '' || status == 'reject'">
              <el-input
                v-if="status == '' || status == 'reject'"
                ref="contact_phone"
                v-model="applyData.contact_phone"
                placeholder="请输入联系手机号"
                name="contact_phone"
                class="h-[48px]"
                style="width: 300px;"
              />
              <div v-else>{{ applyData.contact_phone }}</div>
            </el-form-item>
            <el-form-item label="邮箱地址">
              <el-input
                v-if="status == '' || status == 'reject'"
                ref="contact_email"
                v-model="applyData.contact_email"
                placeholder="请输入邮箱地址"
                name="contact_email"
                class="h-[48px]"
                style="width: 300px;"
              />
              <div v-else>{{ applyData.contact_email }}</div>
            </el-form-item>

            <el-form-item prop="name" label="公司名称" :required="status == '' || status == 'reject'">
              <el-input
                v-if="status == '' || status == 'reject'"
                ref="name"
                v-model="applyData.name"
                placeholder="请输入公司名称"
                name="name"
                class="h-[48px]"
                style="width: 300px;"
              />
              <div v-else>{{ applyData.name }}</div>
            </el-form-item>
            <el-form-item prop="business_license_url" label="营业执照" :required="status == '' || status == 'reject'">
              <el-upload
                v-if="status == '' || status == 'reject'"
                class="avatar-uploader"
                :action="uploadUrl"
                name="file"
                :headers="{'Authorization': accessToken}"
                :before-upload="onBeforeUpload"
                :on-success="onUploadSuccess"
                :on-error="onUploadError"
                :show-file-list="false">
                <img v-if="applyData.business_license_url" :src="applyData.business_license_url" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
              <img v-else :src="applyData.business_license_url" class="avatar"/>
            </el-form-item>
            <el-form-item prop="id_card_1" label="身份证正面" :required="status == '' || status == 'reject'">
              <el-upload
                v-if="status == '' || status == 'reject'"
                class="avatar-uploader"
                :action="uploadUrl"
                name="file"
                :headers="{'Authorization': accessToken}"
                :before-upload="onBeforeUpload"
                :on-success="onUploadSuccess2"
                :on-error="onUploadError"
                :show-file-list="false">
                <img v-if="applyData.id_card_1" :src="applyData.id_card_1" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
              <img v-else :src="applyData.id_card_1" class="avatar"/>
            </el-form-item>
            <el-form-item prop="id_card_2" label="身份证反面" :required="status == '' || status == 'reject'">
              <el-upload
                v-if="status == '' || status == 'reject'"
                class="avatar-uploader"
                :action="uploadUrl"
                name="file"
                :headers="{'Authorization': accessToken}"
                :before-upload="onBeforeUpload"
                :on-success="onUploadSuccess3"
                :on-error="onUploadError"
                :show-file-list="false">
                <img v-if="applyData.id_card_2" :src="applyData.id_card_2" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
              <img v-else :src="applyData.id_card_2" class="avatar"/>
            </el-form-item>

            <el-button
              v-if="status == '' || status == 'reject'"
              :loading="loading"
              type="primary"
              size="large"
              class="w-full"
              style="width: 300px;"
              @click="handleApplySubmit">
              {{ status == 'reject' ? '重新提交' : '提交认证' }}
            </el-button>
          </el-form>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, computed} from "vue"
import AuthAPI, {type ApplyData} from "@/api/auth";
import {getToken} from "@/utils/auth";
import FileAPI from "@/api/file";
import {useUserStore} from "@/store"
import type {UploadProps, UploadUserFile, FormInstance, FormRules} from 'element-plus'

const userStore = useUserStore();
const loading = ref(false);
const uploadUrl = ref(FileAPI.uploadUrl);
const accessToken = ref(getToken());
const applyFormRef = ref<FormInstance>();
const applyData = ref<ApplyData>({
  name: '',
  contact_name: '',
  contact_phone: '',
  contact_email: '',
  business_license_url: '',
  id_card_1: '',
  id_card_2: ''
})

const status = ref(''); //审核状态： ('approve', '审核中'), ('pass', '通过'), ('reject', '拒绝')
const reason = ref(''); //拒绝原因

const applyRules = computed(() => {
  return {
    contact_name: [
      {
        required: true,
        trigger: "blur",
        message: "请输入联系人姓名",
      },
    ],
    contact_phone: [
      {
        required: true,
        trigger: "blur",
        message: "请输入联系人手机号",
      },
    ],
    name: [
      {
        required: true,
        trigger: "blur",
        message: "请输入公司名称",
      },
    ],
    business_license_url: [
      {
        required: true,
        trigger: "blur",
        message: "请上传营业执照",
      },
    ],
    id_card_1: [
      {
        required: true,
        trigger: "blur",
        message: "请上传身份证正面图",
      },
    ],
    id_card_2: [
      {
        required: true,
        trigger: "blur",
        message: "请上传身份证反面图",
      }
    ]
  }
})

const onBeforeUpload: UploadProps['beforeUpload'] = (file) => {
  if (file.type != "image/jpeg" && file.type != "image/png") {
    ElMessage.error('图片类型仅支持PNG,JPG！')
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }
  return true
}

const onUploadSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  ElMessage.success('上传成功');
  applyData.value.business_license_url = response.url;
}
const onUploadSuccess2: UploadProps['onSuccess'] = (response, uploadFile) => {
  ElMessage.success('上传成功');
  applyData.value.id_card_1 = response.url
}
const onUploadSuccess3: UploadProps['onSuccess'] = (response, uploadFile) => {
  ElMessage.success('上传成功');
  applyData.value.id_card_2 = response.url
}
const onUploadError: UploadProps['onError'] = (file) => {
  ElMessage.error('上传失败')
  console.log('error==', file)
}
const getSupplierApplyInfo = () => {
  AuthAPI.supplierApplyInfo().then((res: any) => {
    console.log(res);
    if (res && res.data && res.data.info) {
      status.value = res.data.info.status;
      reason.value = res.data.info.reason;
      Object.assign(applyData.value, res.data.info);
      if(status.value == 'pass' && !userStore.isSupplier){
        userStore.getSupplierInfo();
      }
    }
  })
}
const handleApplySubmit = () => {
  applyFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      AuthAPI.supplierApply(applyData.value).then((res: any) => {
        loading.value = false;
        getSupplierApplyInfo();
        ElMessage.success("提交成功，等待审核~");
      }).catch(error => {
        loading.value = false;
      })
    }
  })
}

onMounted(async () => {
  getSupplierApplyInfo();
});
</script>

<style lang="scss" scoped>
/** 关闭tag标签  */
.app-container {
  /* 50px = navbar = 50px */
  height: calc(100vh - 50px);
  background: var(--el-fill-color-blank);
}


:deep(.avatar-uploader .el-upload) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
  border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 228px;
  height: 128px;
  text-align: center;
}

.avatar {
  width: 228px;
  height: 128px;
}
</style>
